<?php

chdir(dirname(__FILE__)."/../..");
$path = getcwd();
chdir(dirname(__FILE__));

include_once $path."/../lib/core.class.php";
include_once "draw_catalogs.php";


///test

class CatalogPage extends IPlugin 
{
    var $pagespool;

    function CatalogPage($parent = null)
    {
        IPlugin::IPlugin($parent);
        $this->tplfolder = dirname(__FILE__)."/tpl";
        $this->pagespool = null;
        $this->initialize();
    }
    
    function getPluginTag() { return "catalogpage"; }
    function getPluginName() { return "Catalog Page plugin"; }
    function getPluginVersion() { return "1.0.0"; }

    function getProperty($p = null)
    {
        if(null == $p)
        {
            return array("MenuTitle", "MenuBlockTitle");
        }
        $result = "";
        switch ($p)
        {
            case "MenuBlockTitle": { return "Catalog Page render plugin"; } break;
            case "MenuTitle" : { return "catalogpage"; } break;
        };
        return $result;
    }
    
    function initialize()
    {
        $this->pagespool = array();
        if ($handle = opendir($this->tplfolder))
        {
            while (false !== ($file = readdir($handle)))
            {
                if("."==$file || ".."==$file || !file_exists($this->tplfolder."/".$file))
                {
                    continue;
                }
                $fl = split("\.", $file);
                $this->pagespool[] = $fl[0];
            }
            closedir($handle);
        }
        $this->pagespool = array_flip($this->pagespool);
        $core = &getCoreInstance();
        $core->setValues("catalogpage_url", "?".$this->getURL()."&page=");
    }
    
    // ----------------------------------------------------------------------------------
    // --- [ Handling all actions ] -----------------------------------------------------
    // ----------------------------------------------------------------------------------

    function doAction($params)
    {
        if(null != ($result = IPlugin::doAction($params)))
        {
            return $result;
        }

        $core = &getCoreInstance();
        $render = &$core->framework->smarty;
        $db = &$core->getProperty("db");

    
        if (isset($_GET['add_wish_list']))
        {
////debug($db);
////debug($core);
//            $core = & getCoreInstance();
//            $db = $core->getProperty("db");
            $wish_list=$_SESSION['wish_list'];
            $id = $_GET["pid"];
            $cid = $_SESSION['cc']['client_id'];
            $qty = 1;
                if($id>0 && $qty>0)
                {
                    if(isset($wish_list[$id]))
                    {
                        $wish_list[$id]["qty"] += $qty;
                        if(0 == $wish_list[$id]["qty"])
                        {
                            unset($wish_list[$id]);
                        }
                    }
                    else
                    {
                        $core = &getCoreInstance();
                        $db = $core->getProperty("db");
                        $z = $db->getRow("select parent_id, our_price, title, img_small from catalog where catalog_id={$id}");
                        $wish_list[$id] = array(
                                    "qty" => $qty,
                                    "price" => $z["our_price"],
                                    "title" => $z["title"],
                                    "thumbnail" => $z["img_small"],
                                    "id" => $id,
                                    "pid" => $z["parent_id"],
                                    );
                    }
                    
                }
            $wish_list_db=str2db(serialize($wish_list));
////debug($db, $wish_list_db);
            $db->exec("update clients set wish_list='{$wish_list_db}' where client_id={$cid};");
//die();
// //debug("update clients set wish_list='$wish_list_db' where client_id=$cid");
            $_SESSION[wish_list]=$wish_list;
            $GLOBALS[result_]="<font color=\"green\">Product was added to your <a href=\"?path=ccontrl&page=view_wish_list\">Wish List</a></font><br>";
        }
            
        switch ($_POST["event"]) {
           case "doSubmitEmailThis": {
                $msg = "
                <html>
                <body>
                    <b>The Aciannse</b> <br /><br />
                    First Name - {$_POST[first_name]} <br />
                    Last Name - {$_POST[last_name]} <br />
                    Address - {$_POST[address]} <br />
                    E-mail From - {$_POST[email_from]} <br />
                    URL - {$_POST[url_for_email]}
                    Message - {$_POST[message]} <br />
                <body>
                </html>";
                
        $core = &getCoreInstance();
        $mail = $core->getSnippet("email");
           $render = &$core->framework->smarty;
 
    $params = array(
            "html" => "1",            
            "from" => "{$_POST[email_from]}",
        "to"   => "{$_POST[email_to]}", 
        "body" => "$msg",
        "subject" => "{$_POST[last_name]} {$_POST[first_name]} send to you this:");

   
    $render->assign("email", $mail->Render($params));       

                
            } break;   

           case "ask": {
                    ////debug($_POST);
                    $id=$_POST['id'];
                    $item_info=$db->getrow("select catalog_id, title, item_number from catalog where catalog_id=$id");
                    $msg = "
                    <html>
                    <body>
                        <b>Question for the BigAppleJewels.com:</b> <br /><br />
                        <b> Item info:</b>   <br />
                        <a title=\"go to the details page\" href=\"http://BigAppleJewels.com/?path=catalogpage&page=view_details&pid=$item_info[catalog_id]\">catalog_id: \"<b>$item_info[catalog_id]</b>\", title:\"<b>$item_info[title]</b>\", item_number: \"<b>$item_info[item_number]</b>\"</a>
                        <br /> <br />
                        <b> Title of question:</b>   <br />
                        <div style=\"background-color: #efdfff;\"> $_POST[title]</div> <br /> <br />
                        <b> Text of question:</b>
                        <div style=\"background-color: #efdfff;\"> $_POST[ask_text] </div><br /> 
                        
                    <body>
                    </html>";
                    $mail = $core->getSnippet("email");
                    //$render = &$core->framework->smarty;
                    $m_from=$_POST[email];
                    $m_to=$db->getone("select s_value from settings where `s_key`='mail'");//"gendich@ramidus";
                        $m_to = db2str($m_to);
                        if (!isset($m_to) or $m_to == '')
                        $m_to= $core->config['system']['info_email'];

                    
                    $params = array(
                        "to" => $m_to,
                        "from" => $m_from,
                        "body" => $msg,
                        "subject" => " BigAppleJewels question (item:$_POST[id])",
                        "html" => "1",  // 1/0                              
                                    );
                                    
                        $mm=$mail->doAction($params);      
                        $render->assign("question_result", "<br><font color=\"red\"> Your question was successfully sent</font><br>");
               } break;




                case "doSubmitFaqForm" :
                        $faq_id=$db->getone("select max(faq_id) from products_faq where catalog_id=$_GET[pid]")+1;
                        //if (!$testimonial_id) $testimonial_id=0;
                        ////debug($testimonial_id);
                        $sql = "insert into products_faq (catalog_id, faq_id, question, date, user)";
                        $sql .= " values ({$_GET[pid]}, $faq_id, '" . str2db($_POST['faq']) . "', now(), {$_SESSION[cc][client_id]})";
                        $GLOBALS[result_doSubmitFaqForm]="<br><font color=\"green\">Thank you. Your question accepted on consideration by us !</font>";
                        ////debug($sql);
                        $db->Exec($sql);
                        break;
                
                case "doSubmitTestimonialForm" :
                        $testimonial_id=$db->getone("select max(testimonial_id) from products_testimonials where catalog_id=$_GET[pid]")+1;
                        //if (!$testimonial_id) $testimonial_id=0;
                        ////debug($testimonial_id);
                        $sql = "insert into products_testimonials (catalog_id, testimonial_id, text, date, user)";
                        $sql .= " values ({$_GET[pid]}, $testimonial_id, '" . str2db($_POST['testimonial']) . "', now(), {$_SESSION[cc][client_id]})";
                        $GLOBALS[result_doSubmitTestimonialForm]="<br><font color=\"green\">Thank you. Your testimonial accepted on consideration by us !</font>";
                        $db->Exec($sql);
                        break;

        }

    }


// ----------------------------------------------------------------------------------
// --- [ Render pages ] -------------------------------------------------------------
// ----------------------------------------------------------------------------------

    function Render($params)
    {
            global $_G;
        if(null != ($result = IPlugin::Render($params)))
        {
            return $result;
        }
        
        $core = &getCoreInstance();
        $render = &$core->framework->smarty;
        $db = &$core->getProperty("db");
        
        switch ($_G["page"]) {

        /*    case "" :
                header("location: ./");
                break; */

            case "list_catalog" :
                $this->renderListCatalogPage($core, $render, $db);
                $page = "list_catalog.tpl.php";
                break;

            case "all_product" :
                $this->renderAllproducts($core, $render, $db);
                $page = "all_product.tpl.php";
                break;


            case "view_details" :
                $this->renderProductDetailPage($core, $render, $db);
                $page = "productdetail.tpl.php";
                break;

            case "send_on" :
                $this->renderSend_okPage($core, $render, $db);
                $page = "Sendok.tpl.php";
                break;


            case "tell_friend" :
                $this->renderTellFriendPage($core, $render, $db);
                $page = "tellfriend.tpl.php";
                break;
 
            default:
                $this->renderIndexPage($core, $render, $db);
                $page = "list_catalog.tpl.php";
                break;
        }

        
        ////debug($page);
        return $render->fetch("file:".$this->tplfolder."/".$page);
    }



// ----------------------------------------------------------------------------------
// --- [ render tell a friend render start ] -------------------------------------------------------------
// ----------------------------------------------------------------------------------

    function renderListCatalogPage(&$core, &$render, &$db)
    {

        if(!is_numeric($_GET['cid']) && isset($_GET['cid']) && strlen($_GET['cid']) > 0){
        $get_ = split('/',$_GET['cid']);

        $h_title = $get_[max(array_keys($get_))];
        #debug($h_title);
        $rname = ereg_replace('[^a-zA-Z_0-9_-]','',$h_title);

        $id_catalog = $db->getOne("select catalog_id from catalog where is_category = 'Y' and is_active = 'Y' and h_title = '".str2db($rname)."'");
        if($id_catalog > 0 && isset($id_catalog) && is_numeric($id_catalog)){
                $_GET['cid'] = $id_catalog;
        }
        }

        if (isset($_GET["cid"]) and $_GET["cid"] != '' and $_GET['cid'] > 0){
        $id_catalog = $_GET["cid"];
                                                       }
        else {
        header("location: {$core->config["http_root"]}");

        }


                                        /* ... */

        $myclass = & new draw_catalogs($core, $render, $db);
        $mid = $myclass->get_main_parent_id($id_catalog);
//      debug($mid);
//      $id_catalog = $mid;
                                /* ... */

        
    
        $list_catalog = ArrayDb2Str($db->getAll("select catalog_id, title
                                      from catalog 
                                      where parent_id='{$id_catalog}' 
                                        and is_category ='Y'
                                        and is_active='Y'
                                      order by sibling asc"));

        $name_category = db2Str($db->getone("select title from catalog where catalog_id={$_GET['cid']}"));

        $img_category = db2Str($db->getone("select img_small from catalog where catalog_id={$_GET['cid']}"));
        if ($img_category != '' and file_exists($core->config["file_root"] . "/inventory/".$img_category))             
        {$render->assign("img_category", '/inventory/'.$img_category);}        
        else
        {$render->assign("img_category", '/img/pageHeader_prod.gif');}


        $render->assign("name_category", $name_category);        
        
        $render->assign("list_catalog", $list_catalog);
        $num_calogs_col = bcdiv(count($list_catalog), 3);
        $render->assign("num_calogs_col", ($num_calogs_col * 3 < count($list_catalog)) ? $num_calogs_col + 1 : $num_calogs_col);
        $render->assign("num_calogs", count($list_catalog));
        $render->assign("xprice", $_SESSION['xprice']);

        $render->assign("mega_http_root", $core->config["http_root"]);

        $render->assign("this_catalogid", $id_catalog);        

        $x = $this->renderIndexPage(&$core, &$render, &$db);
    
    }


function renderTellFriendPage (&$core, &$render, &$db)
{
$core = &getCoreInstance();

$prod_catalog_id = $_GET['pid'];
$render->assign("prod_cat_id", $prod_catalog_id);

$render->assign("host", $core->config['http_root']);


}

// render tell a friend render end

// ----------------------------------------------------------------------------------
// --- [ render send_ok start ] -------------------------------------------------------------
// ----------------------------------------------------------------------------------


// render send_ok start
function renderSend_okPage (&$core, &$render, &$db)

{

}


// ----------------------------------------------------------------------------------
// --- [ RENDER DETAILS START ] -------------------------------------------------------------
// ----------------------------------------------------------------------------------

function renderProductDetailPage (&$core, &$render, &$db)
{
        if (isset($_GET['pid']) and is_numeric($_GET['pid']) and $_GET['pid'] > 0 ){
                $id_catalog = str2db($_GET["pid"]);
        }
        else{
                if(isset($_GET['pid']) and '' != $_GET['pid'])
                {
                $get_ = split('/',$_GET['pid']);
                $h_title = ereg_replace('[^a-zA-Z_0-9_-]','',$get_[max(array_keys($get_))]);
#                    debug($h_title);exit();
                
                $sql = "select catalog_id from catalog where h_title = '".str2db($h_title)."'";
                $id_catalog = db2str($db->getone($sql));
                        if ($id_catalog == '' or !isset($id_catalog)){
                                header("location:  {$core->config['http_root']}");
                        }
                                $_GET['pid'] = $id_catalog ;

                }
                else{
                        header("location: {$core->config['http_root']}");
                }
        }
       
        /* history links start */

        $render->assign("mega_http_root", $core->config["http_root"]);
if ('' != $id_catalog)
{ 
        $par_cid    = $db->getone('select parent_id from catalog where catalog_id='.$id_catalog);
        $par_htitle = $db->getone("select h_title from catalog where catalog_id='".$par_cid."'");
        
        if ($_GET[cid]=="") $_GET['cid']=$db->getone('select parent_id from catalog where catalog_id='.$id_catalog);
        $render->assign("name_category", $db->getone("select title from catalog where catalog_id=$_GET[cid]"));
        
/*      $str = "$par_htitle";
                if(0 != $str){
                        $str .= '/';
                }
*/      
        $a = $core->config["http_root"];
        $par_titl = $db->getOne("select h_title from catalog where catalog_id = '".$_GET['cid']."'");
        $hs = &$core->getSnippet("historylinks");
        $params = array(
        "startfrom" => $id_catalog,
        "f_id" => "catalog_id",
        "f_parent" => "parent_id",
        "f_title" => "title",
        "table" => "catalog",
        "stopval" => 0, // root                        
       # "url" => "/index?path=catalogpage&cid=###",
        "url" => "/$par_titl.HTM",
        "html_root" => "HOME",
        "html_url" => $core->config['system']['http_root'].'index.html',
        "html_separatop" => " <img src='/img/system/arrow.gif' alt='&rsaquo;' border='0' /> ",
        );
                
        $hs_edit = $hs->Render($params);
        $render->assign("hlinks_", $hs_edit);

        
        /* history links end */
    $prod_details = $db->getone("select `prod_details` from `catalog` where catalog_id={$_GET['pid']}");
    
    $tmp_zz = $prod_details;
    $prod_details = unserialize($tmp_zz);
        if (!is_array($prod_details) || count($prod_details) == 0) {
                $prod_details = "";
        }

    $render->assign("prod_details", $prod_details);
    
    
    
    
    /* Attachment check start */

    $attachment = $this->get_attach_child($id_catalog);
    if ('' != $attachment){
        

        $render->assign("attach_qty", $db->getone("select sum(qty) from store_history where catalog_id='".str2db($attachment)."'"));

        $attach_data = arraydb2str($db->getrow("select * from catalog where catalog_id = '$attachment'"));
        //debug($attach_data);
        if (!file_exists($core->config["file_root"] . "/inventory/" . $attach_data['img_small']) or '' == $attach_data['img_small']){
        $attach_data['img_small'] = "img/no_image.jpg";
        }
        else{
        $attach_data['img_small'] = "inventory/".$attach_data['img_small'];
        }
        $render->assign("attach_data", $attach_data);

    $down_price = $attach_data['our_price'] - $attach_data['list_price'];
    $render->assign("down_price", $down_price);


    }
    else{
        $attach_data = '';
    }
    /* Attachment check ends */
    
     $ttmdiv_on = $_GET['t'];
        if (!isset($ttmdiv_on) or $ttmdiv_on == '' or $ttmdiv_on == '0'){
                $ttmdiv_on = 0;
        }
        else{
                $ttmdiv_on = 1;
        }
                $render->assign("t", $ttmdiv_on);


        if(!isset($id_catalog) or $id_catalog == '')
        header("location: ".$core->config["http_root"]);

    $all_itemdata = ArrayDb2Str($db->getRow("select * from catalog where catalog_id = $id_catalog"));
    $render->assign("img_hires", is_file($core->config["file_root"]."/inventory/".$all_itemdata['img_hires']) ? $all_itemdata['img_hires'] : "");
        $howto = db2str(db2str(
$db->getone("select how_to_use from catalog where catalog_id = $id_catalog")
                        ));     
        $render->assign("howto", $howto);

        $all_itemdata['our_price'] = number_format($all_itemdata['our_price'],2,'.',',');       
        $all_itemdata['list_price'] = number_format($all_itemdata['list_price'],2,'.',','); 
        if ($all_itemdata['list_price']!="" && $all_itemdata['list_price']>0)
                $all_itemdata['stat_price'] = round(100-$all_itemdata['our_price']/$all_itemdata['our_price']*100)."%";
        else $all_itemdata['stat_price'] = "0%";

        if (!file_exists($core->config["file_root"] . "/inventory/" . $all_itemdata['img_large']) || !isne($all_itemdata['img_large']))
                $all_itemdata['img_large'] = '';

    $txt = $this->searchoptimize($all_itemdata['short_desc']);
    $all_itemdata['short_desc'] = $txt;

    $txt = $this->searchoptimize($all_itemdata['description']);
    $all_itemdata['description'] = $txt;

    $render->assign("itemdata", $all_itemdata);
    
     if ($_SESSION[cc][client_id]) $render->assign("logined", "yes"); 


    if (isset($all_itemdata['list_price']) and $all_itemdata['our_price'] > 0 and $all_itemdata['list_price'] > 0){
    $percent = $all_itemdata['our_price']/$all_itemdata['list_price'];
    $percent = 1-$percent;                 

    $percent = $percent*(100);
    $percent = (int) $percent;

    $render->assign("percent", $percent);

                                             }

    $render->assign("cat_id", $id_catalog);
    $this_catalog   = $all_itemdata['parent_id'];
    $this_sibling   = $all_itemdata['sibling'];
        
        if (!isset($this_catalog) or $this_catalog == '')
        $this_catalog = 0;
        
    $prev_sibl_item = $db->getrow("select MAX(catalog_id) as catalog_id from catalog where parent_id = $this_catalog and catalog_id < $id_catalog ORDER BY catalog_id");
    $render->assign("prev_item", $prev_sibl_item);
    $next_sibl_item = $db->getrow("select MIN(catalog_id) as catalog_id from catalog where parent_id = $this_catalog and catalog_id > $id_catalog ORDER BY catalog_id");
    $render->assign("next_item", $next_sibl_item);


        /* 3views vars */

        $sql = "select 
        img_large1 as pi_view1_sm,
        img_hires1 as pi_view1_hi,
        img_large2 as pi_view2_sm,
        img_hires2 as pi_view2_hi,
        img_large3 as pi_view3_sm,
        img_hires3 as pi_view3_hi
        from catalog where catalog_id='".str2db($id_catalog)."'";
        $image = ArrayDb2Str($db->getrow($sql));

        for($i=1; $i<=3; $i++) {
////debug($image["pi_view{$i}_hi"]);
                if(!is_file($core->config["file_root"]."/inventory/".$image["pi_view{$i}_hi"])) {
                        $image["pi_view{$i}_hi"] = "";
                }
        }

        $render->assign("pi", $image);


        $imgsizes = array();
        
        $imgsizes[] = $this->getimgsizes($core->config["file_root"],$all_itemdata['img_hires']);
        $imgsizes[] = $this->getimgsizes($core->config["file_root"],$image['pi_view1_hi']);
        $imgsizes[] = $this->getimgsizes($core->config["file_root"],$image['pi_view2_hi']);
        $imgsizes[]= $this->getimgsizes($core->config["file_root"],$image['pi_view3_hi']);

        $render->assign("imgsizes", $imgsizes);
        
        if (!isset($all_itemdata['parent_id']) or $all_itemdata['parent_id'] == '')
        $all_itemdata['parent_id'] = 0;

        
        $img_category = db2Str($db->getone("select img_small from catalog where catalog_id={$all_itemdata['parent_id']}"));
        if ($img_category != '' and file_exists($core->config["file_root"] . "/inventory/".$img_category))             
        {$render->assign("img_category", "{$core->config["http_root"]}inventory/".$img_category);}        
        else
        {$render->assign("img_category", "{$core->config["http_root"]}img/pageHeader_prod.gif");}


                                                /* GROUPED PRODUCTS START */

        $sql ="select group_with from catalog where catalog_id='".str2db($id_catalog)."'";
        $gw =  db2str($db->getone($sql));
        //debug($gw);
    $sql = "select catalog_id, is_category from catalog where catalog_id in ({$gw}0) order by title asc";
        $gw_arr_data = ArrayDb2Str($db->getAll($sql));

    $arr_items = array();
        foreach ($gw_arr_data as $k => $v ){
                if($v['is_category'] == 'N')
        {
                        $arr_items[] = $v['catalog_id'];
                }
                else
        {
            $sql = "select catalog_id from catalog where parent_id = {$v[catalog_id]} and is_category = 'N'";
                        $items = $db->getAll($sql);
            foreach($items as $item)
                $arr_items[] = $item['catalog_id'];
                }
        }

    if ($arr_items)
        $arr_items = @array_rand(array_flip($arr_items), 3);
    $arr_items[] = 0;
    $sql = "select catalog_id, title, img_small, our_price from catalog where catalog_id in (" . join(",", $arr_items) . ") order by title asc";
    $arr_items = $db->getAll($sql);

    
//debug($arr_items);
    
    foreach ($arr_items as $key_ar => $product_ar)
    {
        if (file_exists($core->config["file_root"] . "/inventory/" . $product_ar['img_small']))
        {
            $arr_items[$key_ar]['img_small'] = "/inventory/" . $product_ar['img_small'];
        }
        else
        {
            $arr_items[$key_ar]['img_small'] = "";
        }
    }

        /* 2do, select random item from each catalog from $catalogs_gdata */


        $render->assign("pline_itms", 4);

        $render->assign("arr_items_group", $arr_items);

    /* GROUPED PRODUCTS END */
    
    // =--------- History products Begin
    
    $history_products = $core->getSnippet("historyproducts");
    $params_history_products = array
    (
        'prod_id' => str2db($id_catalog),
        'limit_records' => 10,
        'user_id' => $_SESSION['cc']['client_id']
    );
    $history_products->insertHistoryRecord($params_history_products);
    // =--------- History products End

    ///---------------------- FAQ, HOW-TO, TESTEMONIALS assign
        $sql = "select * from products_faq, clients where client_id=user and is_active > 0 and catalog_id=".$id_catalog." order by date desc";
        $data = Arraydb2str($db->getall($sql));
        $render->assign("faq", $data);

        $render->assign("cid_", $_SESSION['cc']['client_id']);
    
    if (!count($data)) $GLOBALS[result_doSubmitFaqForm0]="<br><font color=\"red\">No FAQ collected yet.</font><br><br>";
    if (isset($GLOBALS[result_doSubmitFaqForm0]))
    {
        $render->assign("result_doSubmitFaqForm0", $GLOBALS[result_doSubmitFaqForm0]);
        unset($GLOBALS[result_doSubmitFaqForm0]);
    }
        
    if (isset($GLOBALS[result_doSubmitFaqForm]))
    {
        $render->assign("result_doSubmitFaqForm", $GLOBALS[result_doSubmitFaqForm]);
        unset($GLOBALS[result_doSubmitFaqForm]);
    }
    
        
    //---------------------- Testimonials
    $sql = "select products_testimonials.text, products_testimonials.fake_user as fuser, products_testimonials.fake_state as fake_state, clients.client_name, clients.client_billing_state
                    from products_testimonials, clients
                    where products_testimonials.catalog_id = {$id_catalog} and products_testimonials.user = clients.client_id and is_active=1  order by date desc";
    $list_testimonials = $db->getAll($sql);
    $render->assign("list_testimonials", ArrayDb2Str($list_testimonials));
    
    if (!count($list_testimonials)) $GLOBALS[result_doSubmitTestimonialForm0]="<br><font color=\"red\">No testimonials collected yet.</font><br><br>";
    if (isset($GLOBALS[result_doSubmitTestimonialForm0]))
    {
        $render->assign("result_doSubmitTestimonialForm0", $GLOBALS[result_doSubmitTestimonialForm0]);
        unset($GLOBALS[result_doSubmitTestimonialForm0]);
    }
    
    if (isset($GLOBALS[result_doSubmitTestimonialForm]))
    {
        $render->assign("result_doSubmitTestimonialForm", $GLOBALS[result_doSubmitTestimonialForm]);
        unset($GLOBALS[result_doSubmitTestimonialForm]);
    }
    
    //debug($list_testimonials);
    if (isset($GLOBALS[result_]))
    {
        $render->assign("result_", $GLOBALS[result_]);
        unset($GLOBALS[result_]);
    }
    

    if (isne($_SESSION[cc][client_id])){
        $sql = "select client_name, client_billing_state from clients where client_id = {$_SESSION[cc][client_id]}";
        $info_user = $db->getAll($sql);
        $render->assign("info_user", ArrayDb2Str($info_user[0]));
    }
 

    $render->assign("qty", $db->getone("select sum(qty) from store_history where catalog_id='".str2db($id_catalog)."'"));

        
    // ------------------- Warranty Begin ---------------------------
    $sql = "select war_type.warrantytype_id, war_type.warrantytype_name, war_type.warrantytype_description," .
                " war_type.warrantytype_value_months, war_type.warrantytype_price" .
            " from products_warranty as war, products_warranty_types as war_type" .
            " where war.catalog_item_id = {$id_catalog} and war.warranty_type_id = war_type.warrantytype_id and war_type.is_active = 'Y'";
    
    $list_warranty = $db->getAll($sql);
    $render->assign("list_warranty", ArrayDb2Str($list_warranty));
    // ------------------- Warranty End -----------------------------    

} // if end
}

// ----------------------------------------------------------------------------------
// --- [ GET IMAGES SIZE ] ----------------------------------------------------------
// ----------------------------------------------------------------------------------

        function getimgsizes($froot,$img){ 
                if(isne($img) && is_file($froot.'/inventory/'.$img)) {
                        $img = $froot.'/inventory/'.$img;
                        $ar = getimagesize($img);
                        $arrr = $ar[0].','.($ar[1]+50);
                        return $arrr;
                }
                return "";
        } 

// ----------------------------------------------------------------------------------******** ******** ******** ******** ******** ******** ******** ******** ******** ******** ******** ******** ******** ******** 
// --- [ RENDER Index Page ] -------------------------------------------------------------******** ******** ******** ******** ******** ******** ******** ******** ******** ******** ******** ******** ******** ******** 
// ----------------------------------------------------------------------------------******** ******** ******** ******** ******** ******** ******** ******** ******** ******** ******** ******** ******** ******** 

 
    function renderIndexPage(&$core, &$render, &$db)
    {
        if(!is_numeric($_GET['cid']) && isset($_GET['cid']) && strlen($_GET['cid']) > 0){

        $get_ = split('/',$_GET['cid']);

        $h_title = $get_[max(array_keys($get_))];
        #debug($h_title);
        $rname = ereg_replace('[^a-zA-Z_0-9_-]','',$h_title);

        $id_catalog = $db->getOne("select catalog_id from catalog where is_category = 'Y' and is_active = 'Y' and h_title = '".str2db($rname)."'");
        if($id_catalog > 0 && isset($id_catalog) && is_numeric($id_catalog)){
                $_GET['cid'] = $id_catalog;
        }
        }

        if (isset($_GET["cid"]) and $_GET["cid"] != '' and $_GET['cid'] > 0){
        $id_catalog = $_GET["cid"];
                                                       }
        else {
        header("location: {$core->config["http_root"]}");

        }

                                        /* ... */

        $myclass = & new draw_catalogs($core, $render, $db);
        $mid = $myclass->get_main_parent_id($id_catalog);
//      debug($mid);
//      $id_catalog = $mid;
                                /* ... */
    
        $list_catalog = ArrayDb2Str($db->getAll("select catalog_id, title, img_small
                                      from catalog 
                                      where parent_id='{$id_catalog}' 
                                        and is_category ='Y'
                                        and is_active='Y'
                                      order by sibling asc"));
// ----------- check img [
                for ($i=0;$i<count($list_catalog);$i++)
                {
                        if (file_exists($core->config["file_root"]."/inventory/".$list_catalog[$i][img_small]) && is_file($core->config["file_root"]."/inventory/".$list_catalog[$i][img_small])) {
                                list($w_size,$h_size)=explode(',',$this->getimgsizes($core->config["file_root"],$list_catalog[$i][img_small]));
                                //debug($w_size);debug($h_size);
                                $default_w_size=118;
                                $default_h_size=122;
                                $size="";
                                if ($w_size>$h_size && $w_size>$default_w_size)
                                        $size=" width=\"{$default_w_size}px\" ";
                                if ($h_size>$w_size && $h_size>$default_h_size)
//                              $size=" height=\"{$default_h_size}px\" ";
                                
                                $list_catalog[$i]['img_small'] = "<img src=\"/inventory/".$list_catalog[$i][img_small]."\" border=\"0\" alt='Item Image' >";
                        } else {
                                $list_catalog[$i]['img_small'] = "<img src='/img/no_image.gif' border='0' alt='No Item Image' />";
                        }
                }
// ----------- check img ]
        $name_category = db2Str($db->getone("select title from catalog where catalog_id='{$_GET['cid']}'"));

        $img_category = db2Str($db->getone("select img_small from catalog where catalog_id='{$_GET['cid']}'"));
        if ($img_category != '' and file_exists($core->config["file_root"] . "/inventory/".$img_category))             
        {$render->assign("img_category", './inventory/'.$img_category);}        
        else
        {$render->assign("img_category", './img/pageHeader_prod.gif');}


        $render->assign("name_category", $name_category);        
        
        $render->assign("list_catalog", $list_catalog);
        $num_calogs_col = bcdiv(count($list_catalog), 3);
        $render->assign("num_calogs_col", ($num_calogs_col * 3 < count($list_catalog)) ? $num_calogs_col + 1 : $num_calogs_col);
        $render->assign("num_calogs", count($list_catalog));
        $render->assign("xprice", $_SESSION['xprice']);

        $render->assign("mega_http_root", $core->config["http_root"]);

        $render->assign("this_catalogid", $id_catalog);        

        //$x = $this->renderIndexPage(&$core, &$render, &$db);
    
        
        // ******** ******** ******** ******** ******** ******** ******** ******** ******** ******** ******** ******** ******** ******** ******** ******** ******** ******** ******** 
        
        
          if (isset($_GET["cid"]) and $_GET["cid"] > ''){
        $id_catalog = $_GET["cid"];
                             }
        else {
        $id_catalog = 0;
             }
    
        $render->assign("cat_id", $id_catalog);       

        $sql = "select title, ctlg_rows,ctlg_cols,parent_id from catalog where catalog_id ={$id_catalog}";

        $d = $db->getRow($sql);
        
        $all_n_items = $d['ctlg_rows'] * 3;
        
        /* width & heidth of every [catalog_item_td] */

        $p = $core->getSnippet("paging");
        $page = 0;
        $ppg = 0;
        $params = array(
            "source" => "sql",            
            "sql_count" => "select count(*)
                                        from catalog 
                                        where parent_id='{$id_catalog}' 
                                        and 
                                        is_category <>'Y'
                                        and 
                                        is_active = 'Y'",
            "ippg" => $all_n_items,
            "nppv" => 5,
            "urlbase" => $core->config['http_root']."?".$this->getURL()."&cid=".(($id_catalog>=0 && $id_catalog!="") ? $id_catalog : 0),
            "page" => &$page,
            "ppg" => &$ppg,
            );
        $render->assign("paging", $p->Render($params));

        /* Sort params here */

        if (isset($_GET['sortby']) and $_GET['sortby'] != ''){

                $sort = $_GET['sortby'];
                switch($sort){
                        case "lowprice":{
                                $sort = "our_price asc";
                        }break;
                        case "hiprice":{
                                $sort = "our_price desc";
                        }break;
                        case "title":{
                                $sort = "title asc";
                        }break;
                        case "date":{
                                $sort = "catalog_id desc";
                        }break;
                        case "default":{
                                $sort = db2str($db->getone("select catalogs_sorting_sort_by from catalogs_sorting where catalog_sorting_catalog_id = '{$id_catalog}'"));
                        }break;
                        default:{
                                $sort = "sibling asc";
                        }
                }
        }
        else{
                                $sort = db2str($db->getone("select catalogs_sorting_sort_by from catalogs_sorting where catalog_sorting_catalog_id = '{$id_catalog}'"));
        }

        /* Sorting end */
        if(!isset ($sort) or $sort == ''){
         $sort = "sibling";
        }       
        $list_products = ArrayDb2Str($db->getAll("
                                        select *
                                        from catalog 
                                        where parent_id='{$id_catalog}' 
                                        and 
                                        is_category <> 'Y'
                                        and 
                                        is_active='Y'
                                        order by $sort",
                                 0, false, $page==-1 ? 1000000 : $all_n_items, $page==-1 ? 0 : $page*$all_n_items));
// ----------- check img [
//debug($list_products);
                for ($i=0;$i<count($list_products);$i++)
                {
                        if (file_exists($core->config["file_root"]."/inventory/".$list_products[$i][img_small]) && is_file($core->config["file_root"]."/inventory/".$list_products[$i][img_small])) {
                                list($w_size,$h_size)=explode(',',$this->getimgsizes($core->config["file_root"],$list_products[$i][img_small]));
                                $default_w_size=118;
                                $default_h_size=122;
                                $size="";
                                if ($w_size>$h_size && $w_size>$default_w_size)
                                        $size=" width=\"{$default_w_size}px\" ";
                                if ($h_size>$w_size && $h_size>$default_h_size)
//                              $size=" height=\"{$default_h_size}px\" ";
                                
                                $list_products[$i]['img_small'] = "<img src=\"/inventory/".$list_products[$i][img_small]."\" border=\"0\" alt='Item Image' />";
                        } else {
                                $list_products[$i]['img_small'] = "<img src='/img/no_image.jpg' border='0' alt='No Item Image' />";
                        }
                }
// ----------- check img ]
            
        $render->assign("card_co", count($list_products));       

        foreach ($list_products as $k => $v)    {
                $list_products[$k]['our_price'] = number_format($list_products[$k]['our_price'],2,'.',',');     
                $list_products[$k]['list_price'] = number_format($list_products[$k]['list_price'],2,'.',',');   
                $list_products[$k]['short_desc'] = substr($list_products[$k]['short_desc'],0,90).'...';

                                        }       
        
        $render->assign("list_products", $list_products);
   //   $render->assign("show_right_menu", "no");


        $catalog_id = $_GET['cid'];
        if(isne($_GET['cid']))
        {
            if($catalog_id<0 || !is_numeric($catalog_id)){
                header("location: ./?".$this->getURL());
                exit();
            }
        }
        else
        {
            $catalog_id = 0;
        }

        $xcid = $_GET['cid'];
        $cid  = db2str($xcid);
        $par_cid = $db->getone('select parent_id from catalog where catalog_id='.$cid);
//      debug($par_cid);
        $par_htitle = $db->getone("select h_title from catalog where catalog_id='".$par_cid."'");

        $a = $core->config["http_root"];

        $hs = &$core->getSnippet("historylinks");
        $params = array(
        "startfrom" => $catalog_id,
        "f_id" => "catalog_id",
        "f_parent" => "parent_id",
        "f_title" => "title",
        "table" => "catalog",
        "stopval" => 0, // root
        "url" => "?path=catalogpage&cid=###", 
        "html_root" => "Home",
        "html_url" => "/index.html",
        "html_separatop" => " <img src='/img/system/arrow.gif' alt='&rsaquo;' border='0' /> ",
        );
        $hs_edit = $hs->Render($params);
        $render->assign("hlinks", $hs_edit);
//        debug('render_index');
        
        
    }

    /* Custom functions */
    
    /**
     * Will return attachment for item
     *
     * @param int $parent
     * @return array 
     */
    
    function get_attach_child($parent){
        $core = getCoreInstance();
        $db = $core->getProperty("db");
        
        if (is_numeric($parent) and $parent > 0 and '' != $parent){
                $p = str2db($parent);
                $sql = "select products_attach_item_child from products_attach where products_attach_item_parent = '$p'";
                        $child = $db->getone($sql);
                return $child;  
        }
    
        else{    
                        return ("Error: parent not numeric , or < 0, or == '' ");               
        }
    }
   
    function searchoptimize($txt){
        $core    = getCoreInstance();
        $bold_kw = $core->config['searchoptimize']['bold_keywords'];
        $h1_kw = $core->config['searchoptimize']['h1_keywords'];
        $bolds = split(',',$bold_kw);
        $h1s   = split(',',$h1_kw);
        
        if (count($h1s) > 0){
        foreach ($h1s as $n){
        $txt = str_replace("$n","<h1 style='font-size:14px;'>$n</h1>",$txt);
        }
        }

        if (count($bolds) > 0){
        foreach ($bolds as $n){
        $txt = str_replace("$n","<b>$n</b>",$txt);
        }
        }
        return ($txt);  
    }

};


?>
